package cn.edu.baiyunu.myapplication.ui.screens.transactions.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import cn.edu.baiyunu.myapplication.data.model.Category
import cn.edu.baiyunu.myapplication.data.model.Transaction
import cn.edu.baiyunu.myapplication.data.repository.CategoryRepository
import cn.edu.baiyunu.myapplication.data.repository.TransactionRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * 交易详情UI状态
 */
data class TransactionDetailUiState(
    val isLoading: Boolean = true,
    val error: String? = null,
    val transaction: Transaction? = null,
    val category: Category? = null,
    val toastMessage: String = "",
    val navigateBack: Boolean = false,
    val showDeleteDialog: Boolean = false
)

/**
 * 交易详情视图模型
 */
@HiltViewModel
class TransactionDetailViewModel @Inject constructor(
    private val transactionRepository: TransactionRepository,
    private val categoryRepository: CategoryRepository
) : ViewModel() {
    
    private val _uiState = MutableStateFlow(TransactionDetailUiState())
    val uiState: StateFlow<TransactionDetailUiState> = _uiState.asStateFlow()
    
    /**
     * 根据交易ID初始化数据
     */
    fun initWithTransactionId(transactionId: String) {
        if (transactionId.isEmpty()) {
            _uiState.update { 
                it.copy(
                    error = "交易ID不能为空",
                    isLoading = false
                )
            }
            return
        }
        
        viewModelScope.launch {
            try {
                // 加载交易信息
                transactionRepository.getTransactionById(transactionId).collect { transaction ->
                    if (transaction == null) {
                        _uiState.update { 
                            it.copy(
                                error = "找不到该交易记录",
                                isLoading = false
                            )
                        }
                        return@collect
                    }
                    
                    // 更新交易信息
                    _uiState.update { it.copy(transaction = transaction) }
                    
                    // 加载分类信息
                    loadCategory(transaction.categoryId)
                }
            } catch (e: Exception) {
                _uiState.update { 
                    it.copy(
                        error = "加载交易信息失败: ${e.message}",
                        isLoading = false
                    )
                }
            }
        }
    }
    
    /**
     * 加载分类信息
     */
    private fun loadCategory(categoryId: String) {
        viewModelScope.launch {
            try {
                categoryRepository.getCategoryById(categoryId).collect { category ->
                    _uiState.update { 
                        it.copy(
                            category = category,
                            isLoading = false
                        )
                    }
                }
            } catch (e: Exception) {
                _uiState.update { 
                    it.copy(
                        error = "加载分类信息失败: ${e.message}",
                        isLoading = false
                    )
                }
            }
        }
    }
    
    /**
     * 显示删除确认对话框
     */
    fun showDeleteConfirmation() {
        _uiState.update { it.copy(showDeleteDialog = true) }
    }
    
    /**
     * 关闭删除确认对话框
     */
    fun dismissDeleteDialog() {
        _uiState.update { it.copy(showDeleteDialog = false) }
    }
    
    /**
     * 删除当前交易
     */
    fun deleteTransaction() {
        val transaction = _uiState.value.transaction ?: return
        
        viewModelScope.launch {
            try {
                transactionRepository.deleteTransaction(transaction.id)
                _uiState.update { 
                    it.copy(
                        toastMessage = "交易已删除",
                        showDeleteDialog = false
                    )
                }
                
                // 2秒后返回上一页
                kotlinx.coroutines.delay(2000)
                _uiState.update { it.copy(navigateBack = true) }
            } catch (e: Exception) {
                _uiState.update { 
                    it.copy(
                        toastMessage = "删除失败: ${e.message}",
                        showDeleteDialog = false
                    )
                }
            }
        }
    }
    
    /**
     * 清除Toast消息
     */
    fun clearToastMessage() {
        _uiState.update { it.copy(toastMessage = "") }
    }
    
    /**
     * 重置导航状态
     */
    fun resetNavigation() {
        _uiState.update { it.copy(navigateBack = false) }
    }
} 